package com.libservice

import com.libbase.datarepository.DataRepositoryManager
import com.libservice.datarepositories.AuthRepository
import java.util.*

enum class LoginResult(val value: Int) {
    // 登录成功
    SUCCESS(0),

    // 登录错误
    ERROR(1),

    // 已登录
    LOGGED(2);

    companion object {
        fun getByValue(value: Int) = values().firstOrNull { it.value == value }
    }
}

typealias LoginCompletion = (result: LoginResult, message: String?) -> Unit

interface AuthServiceInterface {

    val authRepository: AuthRepository
        get() {
            return DataRepositoryManager.instance.repository(AuthRepository.builder.id) as AuthRepository
        }

    /**
     * 登录
     *
     * @param completion 登录回调
     */
    fun login(completion: LoginCompletion?)

    /**
     * 登出
     */
    fun logout()

    /**
     * 更新token、refreshToken等信息
     */
    fun update(accessToken: String, refreshToken: String, expiredTime: Date) {
        authRepository.update(accessToken, refreshToken, expiredTime)
    }

    /**
     * 未认证
     */
    fun unauthorized(message: String?) {
        authRepository.set(null)

        ServiceManager.instance.routerService.alert(
            "unauthorized",
            "提示",
            message ?: "unauthorized",
            "重新登录",
            false
        ) {
            it?.let {
                ServiceManager.instance.routerService.push("app://page/root", false)
                login(null)
            }
        }
    }
}